<template>
	<view>
		<cu-custom bgColor="bg-green" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">编辑资料</block>
		</cu-custom>
		<form>
			<view class="cu-form-group">
				<view class="title">姓名</view>
				<input placeholder="请输入姓名" name="input" v-model="myFormData.realName"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">用户名</view>
				<input placeholder="用户名" name="input" v-model="myFormData.username" disabled></input>
			</view>
			<view class="cu-form-group">
				<view class="title">头像</view>
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red radius" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">性别</view>
				<switch class='switch-sex green' @change="SwitchC" :class="switchC?'checked':''" :checked="switchC?true:false"></switch>
			</view>
			<view class="cu-form-group">
				<view class="title">生日</view>
				<picker mode="date" :value="myFormData.birthday" @change="DateChange">
					<view class="picker">
						{{myFormData.birthday}}
					</view>
				</picker>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">所属单位</view>
				<input placeholder="所属单位" name="input" v-model="myFormData.departname" disabled></input>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">手机号码</view>
				<input placeholder="输入手机号码" name="input" v-model="myFormData.mobilePhone"></input>
				<view class="cu-capsule radius">
					<view class='cu-tag bg-green '>
						+86
					</view>
					<view class="cu-tag line-green">
						中国大陆
					</view>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">邮箱</view>
				<input placeholder="输入邮箱" name="input"  v-model="myFormData.email"></input>
			</view>
			<view class="padding flex flex-direction">
				<button class="cu-btn bg-green lg"  @click="onSubmit">提交</button>
			</view>
		</form>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				index: -1,
				switchC: true,
				imgList: [],//转换后的图像地址
				tempImgSrc: '',//当前要操作的图片路径，上传或者删除
				uploadUrl:"/appUploadController/dealFile",
				saveUrl:this.$config.apiUrl+"/appUserController/saveUseInfo",
				myFormData:{
					portrait:'',//图像地址
					avatar:'',//转换后图像地址
					realName:'',
					username:'',
					sex:1,
					birthday:'',
					departIds:'',
					departname:'',
					mobilePhone:'',
					email:'',
					id:'',
				},
				dept:{
					id:'',
					departname:''
				},
			};
		},
		onLoad: function (option) {
			// console.log("this.$Route.query",this.$Route.query);
			let query=this.$Route.query
			if(query){
				this.myFormData=query;
				if(this.myFormData.sex=='女'){
				  this.switchC = false
				}else if(this.myFormData.sex=='男'){
				  this.switchC = true
				}
				if(this.myFormData.avatar){
				  this.imgList=this.myFormData.avatar.split(",");
				}
				if(this.myFormData.portrait){
				  this.imageSrc=this.myFormData.portrait.split(",");
				}
				if(!this.myFormData.birthday){
				  this.myFormData.birthday= '无'
				}
	
				Object.keys(this.myFormData).map(key=>{
				  if(this.myFormData[key]=='无'){
					this.myFormData[key] = ''
				  }
				})
				// console.log("this.myFormData",this.myFormData)
			}
		},
		methods: {
			onSubmit() {
			  let myForm = this.myFormData
			  let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
			  let checkEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
			  if(!myForm.mobilePhone || myForm.mobilePhone.length==0){
				this.$tip.alert('请输入手机号');
				return false
			  }
			  if(!checkPhone.test(myForm.mobilePhone)){
				this.$tip.alert('请输入正确的手机号');
				return false
			  }
			  if(!checkEmail.test(myForm.email)){
				this.$tip.alert('请输入正确的邮箱地址');
				return false
			  }
				this.myFormData.id = this.$store.getters.userid
				if(this.switchC){
					this.myFormData.sex=0//男
				}else{
					this.myFormData.sex=1
				}
				// console.log('myform',this.myFormData)
				this.$tip.loading();
				this.$http.post(this.saveUrl,this.myFormData).then(res=>{
					// console.log(res)
					this.$tip.loaded();
					if (res.data.ok){
						this.$tip.toast('提交成功')
						setTimeout(() => {
							//派发刷新事件
							uni.$emit('reloadPsnInfo', {msg:'刷新'});
							this.$Router.replace({name:'index'})
						}, 1000)
					}
				}).catch(()=>{
					this.$tip.loaded();
					this.$tip.error('提交失败')
				});
			},
			DateChange(e) {
				this.myFormData.birthday = e.detail.value
			},
			SwitchC(e) {
				this.switchC = e.detail.value
			},
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						//console.log("ChooseImage",res.tempFilePaths);
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						this.tempImgSrc=res.tempFilePaths[0];
						// console.log("tempImgSrc",this.tempImgSrc);
						this.dealFile(1,0,'');
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除照片',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if(this.myFormData.id){
								let lj=this.imgList[e.currentTarget.dataset.index];
								let index=lj.indexOf("server");
								this.tempImgSrc=lj.substring(index+7,lj.length);
								this.dealFile(0,1,this.tempImgSrc);
							}
							// console.log("delPath",this.tempImgSrc);
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			//处理附件
			dealFile(isup,isdel,delPath){
				uni.uploadFile({
				    url: this.$config.apiUrl+"/appUploadController/dealFile",
					filePath: this.tempImgSrc,//本地文件路径或者已存储的相对路径
					fileType: 'image',
					name: 'file',//后端通过'file'获取上传的文件对象
				    formData: {
						isup:isup,
						isdel:isdel,
						bizType:'photosucai',
						delPath:delPath
					},
				    success: (res) => {
						// console.log(res)
				        if (res.statusCode === 200) {
							let data=JSON.parse(res.data);
							let msg=data.message;
							this.myFormData.portrait=data.data;
							// console.log(this.myFormData.portrait);
				            uni.showToast({
				                title: msg,
								duration: 2000
				            });
							this.tempImgSrc="";
				        }
				    },
				    fail: (res) => {
				        console.log(res)
				    }
				});
			}
		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
